//
//  URLManager.m
//  ZDSC
//
//  Created by ZDTX on 2021/5/12.
//

#import "URLManager.h"
#import "API.h"
#import "LogCategory.h"
#import "NSDictionary+Null.h"
#import "ZYCLoginViewController.h"
#import "ZYCNavigationController.h"

@implementation URLManager

static URLManager *_instanceType = nil;

+ (instancetype)sharedURLManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instanceType = [URLManager manager];
        _instanceType.requestSerializer = [AFJSONRequestSerializer serializer];
        NSString *platform = @"iOS";
        [_instanceType.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [_instanceType.requestSerializer setValue:platform forHTTPHeaderField:@"platform"];
        _instanceType.requestSerializer.HTTPShouldHandleCookies = YES;
        _instanceType.requestSerializer.timeoutInterval = 180.0f;
        _instanceType.responseSerializer = [AFJSONResponseSerializer serializer];
        _instanceType.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",nil];
    });
    return _instanceType;
}


- (void)getUrlString:(NSString *_Nullable)urlString
            requestService:(RequestService)requestService
                parameters:(NSDictionary *_Nullable)parameters
                  progress:(void(^_Nullable)(NSProgress * _Nonnull downloadProgress))progress
                   success:(void(^_Nullable)(id _Nullable responseObject))success
             failure:(void(^_Nullable)(NSError * _Nonnull error))failure{
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"Authorization"]) {
        [self.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"Authorization"]  forHTTPHeaderField:@"Authorization"];
    }
    NSString *urlStr;
    // 邹勇
//    if (requestService == RequestServiceSystem) {
//        urlStr = [NSString stringWithFormat:@"zd-system-service/%@",urlString];
//    }else if(requestService == RequestServiceWorkBench){
//        urlStr = [NSString stringWithFormat:@"zy-sdfz-workbench-service/%@",urlString];
//    }else if(requestService == RequestServiceMessage){
//        urlStr = [NSString stringWithFormat:@"zy-message-service/%@",urlString];
//    }else if(requestService == RequestServiceActiviti){
//        urlStr = [NSString stringWithFormat:@"yzou-sdfz-activiti-service/%@",urlString];
//    }
    // 易毅
//    if (requestService == RequestServiceSystem) {
//        urlStr = [NSString stringWithFormat:@"yiyi-sdfz-system-service/%@",urlString];
//    }else if(requestService == RequestServiceWorkBench){
//        urlStr = [NSString stringWithFormat:@"yiyi-sdfz-workbench-service/%@",urlString];
//    }else if(requestService == RequestServiceMessage){
//        urlStr = [NSString stringWithFormat:@"yiyi-sdfz-message-service/%@",urlString];
//    }else if(requestService == RequestServiceActiviti){
//        urlStr = [NSString stringWithFormat:@"yiyi-sdfz-activiti-service/%@",urlString];
//    }
//
    // 郭彬
//    if (requestService == RequestServiceSystem) {
//        urlStr = [NSString stringWithFormat:@"gb-sdfz-system-service/%@",urlString];
//    }else if(requestService == RequestServiceWorkBench){
//        urlStr = [NSString stringWithFormat:@"gb-sdfz-workbench-service/%@",urlString];
//    }else if(requestService == RequestServiceMessage){
//        urlStr = [NSString stringWithFormat:@"gb-sdfz-message-service/%@",urlString];
//    }
    
    // 测试环境
    if (requestService == RequestServiceSystem) {
        urlStr = [NSString stringWithFormat:@"zd-system-service/%@",urlString];
    }else if(requestService == RequestServiceWorkBench){
        urlStr = [NSString stringWithFormat:@"zd-workbench-service/%@",urlString];
    }else if(requestService == RequestServiceMessage){
        urlStr = [NSString stringWithFormat:@"zd-message-service/%@",urlString];
    }else if(requestService == RequestServiceActiviti){
        urlStr = [NSString stringWithFormat:@"zd-activiti-service/%@",urlString];
    }
    NSLog(@"\n【url: %@】\n【parameters:\n %@】",urlStr,parameters);
    [self GET:[NSString stringWithFormat:@"%@/%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],urlStr] parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSDictionary processDictionaryIsNSNull:responseObject];
        NSLog(@"\n responseObject: %@ \n",dict);
        if ([responseObject[@"code"] integerValue] == kTokenExpired) {
            ZYCLoginViewController *vc = [[ZYCLoginViewController alloc]init];
            ZYCNavigationController *nav = [[ZYCNavigationController alloc]initWithRootViewController:vc];
            [[[UIApplication sharedApplication] delegate] window].rootViewController = nav;
            [[[[UIApplication sharedApplication] delegate] window] makeKeyAndVisible];
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"kLoginFlag"];
        }
        if (success) {
            success(dict);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"\n error: %@ \n" ,error);
        [MrjSVProgressHUD showErrorWithStatus:@"网络异常"];
//        NSLog(@"网络异常");
//        if (failure) {
//            failure(error);
//        }
    }];
}


- (void)postUrlString:(NSString *_Nullable)urlString
            requestService:(RequestService)requestService
                parameters:(NSDictionary *_Nullable)parameters
                  progress:(void(^_Nullable)(NSProgress * _Nonnull downloadProgress))progress
                   success:(void(^_Nullable)(id _Nullable responseObject))success
              failure:(void(^_Nullable)(NSError * _Nonnull error))failure{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"Authorization"]) {
        [self.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"Authorization"]  forHTTPHeaderField:@"Authorization"];
    }
    NSString *urlStr;
    // 邹勇
//    if (requestService == RequestServiceSystem) {
//        urlStr = [NSString stringWithFormat:@"zd-system-service/%@",urlString];
//    }else if(requestService == RequestServiceWorkBench){
//        urlStr = [NSString stringWithFormat:@"zy-sdfz-workbench-service/%@",urlString];
//    }else if(requestService == RequestServiceMessage){
//        urlStr = [NSString stringWithFormat:@"zy-message-service/%@",urlString];
//    }else if(requestService == RequestServiceActiviti){
//        urlStr = [NSString stringWithFormat:@"yzou-sdfz-activiti-service/%@",urlString];
//    }
    
    // 易毅
//    if (requestService == RequestServiceSystem) {
//        urlStr = [NSString stringWithFormat:@"yiyi-sdfz-system-service/%@",urlString];
//    }else if(requestService == RequestServiceWorkBench){
//        urlStr = [NSString stringWithFormat:@"yiyi-sdfz-workbench-service/%@",urlString];
//    }else if(requestService == RequestServiceMessage){
//        urlStr = [NSString stringWithFormat:@"yiyi-sdfz-message-service/%@",urlString];
//    }else if(requestService == RequestServiceActiviti){
//        urlStr = [NSString stringWithFormat:@"yiyi-sdfz-activiti-service/%@",urlString];
//    }
    
    
    // 郭彬
//    if (requestService == RequestServiceSystem) {
//        urlStr = [NSString stringWithFormat:@"gb-sdfz-system-service/%@",urlString];
//    }else if(requestService == RequestServiceWorkBench){
//        urlStr = [NSString stringWithFormat:@"gb-sdfz-workbench-service/%@",urlString];
//    }else if(requestService == RequestServiceMessage){
//        urlStr = [NSString stringWithFormat:@"gb-sdfz-message-service/%@",urlString];
//    }
    // 测试环境
    if (requestService == RequestServiceSystem) {
        urlStr = [NSString stringWithFormat:@"zd-system-service/%@",urlString];
    }else if(requestService == RequestServiceWorkBench){
        urlStr = [NSString stringWithFormat:@"zd-workbench-service/%@",urlString];
    }else if(requestService == RequestServiceMessage){
        urlStr = [NSString stringWithFormat:@"zd-message-service/%@",urlString];
    }else if(requestService == RequestServiceActiviti){
        urlStr = [NSString stringWithFormat:@"zd-activiti-service/%@",urlString];
    }
    
    NSLog(@"\n【url: %@】\n【parameters:\n %@】",urlStr,parameters);
    [self POST:[NSString stringWithFormat:@"%@/%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],urlStr] parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        if (uploadProgress) {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSDictionary processDictionaryIsNSNull:responseObject];
        NSLog(@"\n responseObject: %@ \n",dict);
        
        if ([responseObject[@"code"] integerValue] == kTokenExpired) {
            ZYCLoginViewController *vc = [[ZYCLoginViewController alloc]init];
            ZYCNavigationController *nav = [[ZYCNavigationController alloc]initWithRootViewController:vc];
            [[[UIApplication sharedApplication] delegate] window].rootViewController = nav;
            [[[[UIApplication sharedApplication] delegate] window] makeKeyAndVisible];
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"kLoginFlag"];
        }
        if (success) {
            success(dict);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"\n error: %@ \n" ,error);
        [MrjSVProgressHUD showErrorWithStatus:@"网络异常"];
        if (failure) {
            failure(error);
        }
    }];
    
}


-(void)uploadImageWithUrlString:(NSString *)urlStr
                     parameters:(NSDictionary *)parameters
                     imageArray:(NSArray *)imageArray
                        success:(void(^_Nullable)(id _Nullable responseObject))success
                        failure:(void(^_Nullable)(NSError * _Nonnull error))failure
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"Authorization"]) {
        [self.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"Authorization"]  forHTTPHeaderField:@"Authorization"];
    }
    NSLog(@"%@--%@",urlStr,parameters);
    
    [self POST:urlStr parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i=0; i<imageArray.count; i++) {
            NSDictionary *dic = imageArray[i];
            [formData appendPartWithFileData:dic[@"data"] name:dic[@"key"] fileName:[NSString stringWithFormat:@"upload%d.png",i] mimeType:@"image/png"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSDictionary processDictionaryIsNSNull:responseObject];

        if (success) {
            success(dict);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    

}


@end
